package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.OrderTypeSelectVo;
import com.zb.entity.SelectVo;
import com.zb.entity.ZjWorkModuleType;
import com.zb.entity.ZjWorkModuleWay;
import com.zb.mapper.ZjWorkModuleWayMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkDetailService;
import com.zb.service.ZjWorkModuleWayService;
import com.zb.vo.WorkModuleTypeListVo;
import com.zb.vo.WorkModuleWayListVo;
import com.zb.vo.WorkModuleWayVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单处理方式表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-16
 */
@Service
public class ZjWorkModuleWayServiceImpl extends ServiceImpl<ZjWorkModuleWayMapper, ZjWorkModuleWay> implements ZjWorkModuleWayService {
    @Resource
    private ZjWorkModuleWayMapper workModuleWayMapper;
    @Resource
    private ZjWorkDetailService workDetailService;

    // 新增或修改工单处理方式
    @Override
    public void save(Long custAccId, Long moduleId, WorkModuleWayVo workModuleWayVo) {
        Assert.isTrue(null == workModuleWayMapper.existByName(custAccId, moduleId, workModuleWayVo.getId(), workModuleWayVo.getName()), "处理方式名称已重复");
        ZjWorkModuleWay way = new ZjWorkModuleWay();
        BeanUtils.copyProperties(workModuleWayVo, way);
        way.setDisabled(workModuleWayVo.getStatus());
        if (null != way.getId()) {
            this.updateById(way);
            return;
        }
        way.setId(IdWorker.getId());
        way.setCustAccId(custAccId);
        way.setModuleId(moduleId);
        this.save(way);
    }

    // 获取处理方式列表
    @Override
    public Map<String, Object> getList(Long moduleId, SelectVo selectVo) {
        QueryWrapper<ZjWorkModuleWay> wrapper = new QueryWrapper<>();
        wrapper.eq("module_id", moduleId).eq("parent_id", 0);
        wrapper.orderByDesc("sort", "gmt_update");
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setPageLimit(selectVo);
        Page<ZjWorkModuleWay> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);

        wrapper = new QueryWrapper<>();
        wrapper.eq("module_id", moduleId).gt("parent_id", 0);
        List<ZjWorkModuleWay> childWays = this.list(wrapper);

        List<WorkModuleWayListVo> voList = page.getRecords().stream().map(way -> {
            WorkModuleWayListVo vo = new WorkModuleWayListVo();
            BeanUtils.copyProperties(way, vo);
            vo.setLevel(1);
            vo.setStatus(way.getDisabled());
            vo.setCreateTime(way.getGmtCreate());
            vo.setUpdateTime(way.getGmtUpdate());
            vo.setChildWays(getChildWay(way.getId(), 2, childWays));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    /**
     * 获取子级处理方式
     * @param id
     * @param childWays
     * @return
     */
    private List<WorkModuleWayListVo> getChildWay(Long id, Integer level, List<ZjWorkModuleWay> childWays) {
        return childWays.stream().filter(ct -> Objects.equals(id, ct.getParentId())).map(type -> {
            WorkModuleWayListVo vo = new WorkModuleWayListVo();
            BeanUtils.copyProperties(type, vo);
            vo.setLevel(level);
            vo.setStatus(type.getDisabled());
            vo.setCreateTime(type.getGmtCreate());
            vo.setUpdateTime(type.getGmtUpdate());
            vo.setChildWays(getChildWay(type.getId(), 3, childWays));
            return  vo;
        }).toList();
    }

    // 根据ID批量启用或禁用模块处理方式
    @Override
    public void updateDisabledBatchById(List<Long> ids, boolean status) {
        workModuleWayMapper.updateDisabledBatchById(ids, status);
    }

    // 根据ID批量删除模块处理方式
    @Override
    public void deleteBatchById(List<Long> ids) {
        List<Long> wayIds = workDetailService.getByWayIds(ids);
        if (!wayIds.isEmpty()) {
            String ways = workModuleWayMapper.getByIds(wayIds).stream().map(ZjWorkModuleWay::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "处理方式[" + ways + "]已与工单关联，不可删除");
        }
        List<Long> removeIds = workModuleWayMapper.getByIds(ids).stream().map(ZjWorkModuleWay::getId).toList();
        this.removeByIds(removeIds);
    }

    // 工单模块处理方式下拉列表查询
    @Override
    public Map<String, Object> workModuleWayPageSelect(Long moduleId, SelectVo selectVo) {
        QueryWrapper<ZjWorkModuleWay> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.eq("module_id", moduleId).eq("parent_id", 0).eq("is_disabled", false);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setSelectPageLimit(selectVo);
        Page<ZjWorkModuleWay> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<Long> ids = page.getRecords().stream().map(ZjWorkModuleWay::getId).toList();

        List<ZjWorkModuleWay> types = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            types.addAll(workModuleWayMapper.getByParentIds(ids));
        }
        List<OrderTypeSelectVo> voList = page.getRecords().stream().map(type -> {
            OrderTypeSelectVo vo = new OrderTypeSelectVo(type.getId(), type.getName());
            vo.setSelectVos(getChild(vo.getId(), types));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    public List<OrderTypeSelectVo> getChild(Long id, List<ZjWorkModuleWay> childways) {
        return childways.stream().filter(type -> Objects.equals(id, type.getParentId())).map(t -> {
            OrderTypeSelectVo vo = new OrderTypeSelectVo(t.getId(), t.getName());
            vo.setSelectVos(getChild(vo.getId(), childways));
            return vo;
        }).toList();
    }

    // 根据模块处理方式ID获取方式名称
    @Override
    public String getNameByIds(Long oneWayId, Long twoWayId, Long threeWayId) {
        if (null == oneWayId) {
            return "";
        }
        List<Long> ids = new ArrayList<>();
        ids.add(oneWayId);
        if (null != twoWayId) ids.add(twoWayId);
        if (null != threeWayId) ids.add(threeWayId);
        return workModuleWayMapper.getNameByIds(ids);
    }


}
